# Copyright (c) 2024, lanlian and contributors
# For license information, please see license.txt

import json

import frappe
from frappe import _, msgprint
from frappe.model.mapper import get_mapped_doc
from frappe.utils import cint, cstr, flt
from frappe.model.document import Document


class EMSMaintenancePlan(Document):
	# 提交前检验: 同一个设备只能有一个提交状态,并且是否停止等于0,并且频率相同的(不同频率,比如月保养和年度保养可以共存)
	def before_submit(self):
		if frappe.db.exists({"doctype": self.doctype, "equipment_card": self.equipment_card, "is_stoped": 0, "docstatus": 1, "periodicity": self.periodicity}):
			frappe.throw(_("EMS Maintenance Plan {0} Is Running. The BillNo is:{1}").format(self.periodicity, frappe.db.exists({"doctype": self.doctype, "equipment_card": self.equipment_card, "is_stoped": 0, "docstatus": 1, "periodicity": self.periodicity})))

	def on_cancel(self):
		frappe.db.set_value(self.doctype, self.name, {"is_stoped": 1})
		self.reload()



# 保养方案生成保养单
@frappe.whitelist()
def make_maintenance_doc(source_name, target_doc=None, args=None):
	doc = get_mapped_doc(
		"EMS Maintenance Plan",
		source_name,
		{
			"EMS Maintenance Plan": {
				"doctype": "EMS Maintenance Doc",
				"field_map": {"name": "maintenance_plan", "start_date": "expected_maintenance_date"},
				"validation": {"docstatus": ["=", 1], "is_stoped": ["=", 0]},
			},
			"EMS Maintenance Plan Item": {
				"doctype": "EMS Maintenance Doc Item",
				"field_map": {},
			},
			"EMS Maintenance Plan Item Parts": {
				"doctype": "EMS Maintenance Doc Item Parts",
				"field_map": {},
			},
		},
		target_doc,
		ignore_permissions=True,
	)
	# 修改预计保养日期
	doc.expected_maintenance_date = frappe.utils.getdate()

	return doc


# 后台计划生成保养单
@frappe.whitelist()
def make_maintenance_doc_schedule():
	plans = frappe.db.get_all('EMS Maintenance Plan', filters={"is_stoped": 0, "docstatus": 1})
	for i in plans:
		# 先判断当前保养方案是否已经有生成过保养单: 如果没生成过则不自动生成
		if frappe.db.exists({"doctype": "EMS Maintenance Doc", "maintenance_plan": i.name}):
			# 找到最后一张(根据预计保养日期排序)保养单的下个保养日期
			last_maintenance_next_date = frappe.db.get_all(	"EMS Maintenance Doc", 
											filters={"maintenance_plan": i.name,"maintenance_stoped": 0},
											fields=["maintenance_next_date"],
											order_by="expected_maintenance_date desc",
											page_length=1,
										)
			# 判断下个保养日期是否小于或等于(按照正常业务逻辑应该就等于今天日期),满足条件则自动生成当天的保养单
			if last_maintenance_next_date[0]["maintenance_next_date"] <= frappe.utils.getdate():
				source_name=i.name
				target_doc=None
				doc = get_mapped_doc(
					"EMS Maintenance Plan",
					source_name,
					{
						"EMS Maintenance Plan": {
							"doctype": "EMS Maintenance Doc",
							"field_map": {"name": "maintenance_plan", "start_date": "expected_maintenance_date"},
							"validation": {"docstatus": ["=", 1], "is_stoped": ["=", 0]},
						},
						"EMS Maintenance Plan Item": {
							"doctype": "EMS Maintenance Doc Item",
							"field_map": {},
						},
						"EMS Maintenance Plan Item Parts": {
							"doctype": "EMS Maintenance Doc Item Parts",
							"field_map": {},
						},
					},
					target_doc,
					ignore_permissions=True,
				)
				# 修改预计保养日期
				doc.expected_maintenance_date = frappe.utils.getdate()
				print(doc.name)
				doc.save()
